<template>
  <div class='dashboard-container'>
    <div class="app-container">
      <el-card>
        <!-- 搜索 -->
        <el-row>
            <el-form :inline="true" :model="page" ref="searchForm">
              <el-col :span="16">
                <el-form-item label="关键字">
                  <el-input v-model="page.keyword" placeholder="根据文章标题搜索" clearable style="width: 200px;margin-right: 40px;"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="page.state" placeholder="请选择" clearable @clear="page.state = null"
                    style="width: 200px; margin-right: 40px;">
                    <el-option label="启用" :value="1"></el-option>
                    <el-option label="禁用" :value="0"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button size="small" @click="clearBtn">清除</el-button>
                  <el-button size="small" type="primary" @click="searchBtn">搜索</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="8" style="text-align: right;">
                <el-button size="small" type="success" icon="el-icon-edit"
                  @click="editArticle({ id: 'add' })">新增技巧</el-button>
              </el-col>
            </el-form>
          </el-row>
        <!-- 提示 -->
        <el-alert :title='`数据一共 ${total} 条`' type="info" show-icon :closable="false" style="margin-bottom: 15px;" />
        <!-- 表格列表 -->
        <el-table :data="list" v-loading="tabLoading">
          <el-table-column label="序号" type="index" />
          <el-table-column label="文章标题" prop="title">
            <template v-slot="{ row }">
              {{ row.title }} <i v-if="row.videoURL" class="el-icon-film" @click="loadVideo(row.videoURL)" />
            </template>
          </el-table-column>
          <el-table-column label="阅读数" prop="visits" />
          <el-table-column label="录入人" prop="username" />
          <el-table-column label="录入时间" prop="createTime">
            <template v-slot="{ row }">
              {{ row.createTime | parseTime }}
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="state">
            <template v-slot="{ row }">
              {{ row.state === 1 ? '已启用' : '已禁用' }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="articlePreview(row)">预览</el-button>
              <el-button type="text" size="small" @click="changeState(row)">{{ row.state === 1 ? '禁用' : '启用'
              }}</el-button>
              <el-button type="text" size="small" :disabled="row.state === 1" @click="editArticle(row)">修改</el-button>
              <el-button type="text" size="small" :disabled="row.state === 1" @click="delArticle(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination background @current-change="pageChange" @size-change="sizeChange" :current-page="+page.page"
          :total="total" :page-size="+page.pagesize" :page-sizes="[1, 5, 10, 20]" layout="prev, pager, next,sizes, jumper"
          style="margin-top: 15px; text-align: right;"></el-pagination>
      </el-card>
      <!-- 添加文章对话框 -->
      <articles-add ref="articlesAdd" :show-add-dialog.sync="showAddDialog" @articlesAdd="getArticlesList"
        :articles-data="articlesData" @pageChange="pageChange" />
      <!-- 预览文章对话框 -->
      <articles-preview :preview-dialog.sync="previewDialog" :article-detail="articleDetail" />

      <!-- 视频预览窗口 -->
      <div class="video-box" v-if="showVideo">
        <el-tooltip class="item" effect="dark" content="关闭" placement="top">
          <div class="close" @click="showVideo = false">
            <i class="el-icon-close"></i>
          </div>
        </el-tooltip>
        <div class="video">
          <video-player class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true"
            :options="playerOptions" />
        </div>
      </div>
    </div>
    <!-- 视频遮罩层 -->
    <div class="mask" v-if="showVideo"></div>
  </div>
</template>

<script>
import articlesAdd from '../components/articles-add.vue';
import articlesPreview from '../components/articles-preview.vue';
import { list, detail, remove, changeState } from "@/api/hmmm/articles";
// 视频组件
import { videoPlayer } from 'vue-video-player'
import 'video.js/dist/video-js.css'
// 引入lodash
import _ from 'lodash'
export default {
  components: {
    articlesAdd,
    articlesPreview,
    videoPlayer
  },
  data () {
    return {
      // 视频播放器配置项
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: false,  // 如果为true,浏览器准备好时开始回放
        muted: false,     // 默认情况下将会消除任何音频。
        loop: false,      // 是否视频一结束就重新开始。
        preload: 'auto',  // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9',  // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true,  // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: "",  // 类型
          src: ''  // url地址
        }],
        notSupportedMessage: '此视频暂无法播放，请稍后再试',  // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,           // 当前时间和持续时间的分隔符
          durationDisplay: true,       // 显示持续时间
          remainingTimeDisplay: false, // 是否显示剩余时间功能
          fullscreenToggle: true       // 是否显示全屏按钮
        }
      },
      showVideo: false,  // 视频窗口显示
      page: {
        page: 1,  // 当前页数
        pagesize: 10,  // 每页显示的数据条数
        keyword: '',  // 搜索关键字
        state: null,  // 状态
      },
      articlesData: {
        title: '',  // 文章标题
        articleBody: '',  // 文章内容
        videoURL: ''  // 视频地址
      },
      total: 0,  // 数据总条数
      list: [],  // 数据
      showAddDialog: false,  // 新增弹窗
      previewDialog: false,  // 预览弹窗
      articleDetail: {},  // 文章详情
      tabLoading: false  // 数据列表加载状态

    }
  },
  created () {
    this.getArticlesList()
  },
  methods: {
    // 获取数据列表
    async getArticlesList () {
      this.tabLoading = true
      const { data: res } = await list(this.page)
      // console.log(res);
      this.list = res.items
      this.page.page = res.page
      this.page.pagesize = res.pagesize
      this.total = res.counts
      this.tabLoading = false
    },
    // 换页
    pageChange (newPage) {
      this.page.page = newPage  // 将最新页码给当前页
      this.getArticlesList()  // 重新获取数据
    },
    // 切换每页显示的数据条数
    sizeChange (newPageSize) {
      // console.log(newPageSize);
      this.page.pagesize = newPageSize
      this.getArticlesList()
    },
    // 清除
    clearBtn () {
      this.page.keyword = ''
      this.page.state = null
    },
    // 搜索
    searchBtn: _.throttle(function () {
      this.getArticlesList()

    }, 1000),
    // 文章预览
    async articlePreview (data) {
      // data 就是所点击的文章数据
      this.articleDetail = data
      this.previewDialog = true  // 开启预览弹窗
    },
    // 新增、修改弹窗
    async editArticle (data) {
      this.showAddDialog = true // 开启弹窗
      // 判断是新增还是修改
      if (data.id === 'add') {
        // 新增
        // console.log('新增');
        this.articlesData = {
          title: '',
          articleBody: '',
          videoURL: ''
        }
      } else {
        // 修改
        this.$refs.articlesAdd.loading = true
        const { data: res } = await detail(data)
        // console.log(res);
        this.articlesData = res
        this.$nextTick(() => {
          this.$refs.articlesAdd.loading = false
        })
      }
    },
    // 删除
    async delArticle (data) {
      try {
        await this.$confirm('确认删除此文章吗？', '提示', { type: 'warning' })
        // 如果删除的时候页面只有一条数据时 跳到上一页
        if (this.list.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        await remove(data)
        this.$message.success('删除成功！')
        this.getArticlesList()

      } catch (error) {
        console.log(error);
      }
    },
    // 禁用  启用按钮   添加 lodash 节流方法
    changeState: _.throttle(async function (data) {
      // console.log(data);
      if (data.state === 1) {
        data.state = 0
        await changeState(data)
        this.$message.success('已禁用')
      } else {
        data.state = 1
        await changeState(data)
        this.$message.success('已启用')
      }
    }, 1000),
    // 播放视频
    loadVideo (url) {
      this.showVideo = true
      this.playerOptions['sources'][0]['src'] = url;
    }
  }
}
</script>

<style scoped lang='scss'>
.el-icon-film {
  color: blue;
}
.mask {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba($color: #000, $alpha: 0.6);
  z-index: 1002;
}

.video-box {
  position: fixed;
  z-index: 2000;
  top: 160px;
  left: 50%;
  transform: translateX(-600px);

  .video {
    z-index: 2001;
    width: 1200px;
    border-radius: 20px;
    overflow: hidden;
  }


  .close {
    position: absolute;
    top: -80px;
    left: 50%;
    z-index: 2001;
    width: 50px;
    height: 50px;
    text-align: center;
    transform: translateX(-25px);
    background-color: rgba($color: #000, $alpha: 0.6);
    border-radius: 50%;

    .el-icon-close {
      display: block;
      line-height: 50px;
      color: #fff;
      font-size: 30px;
    }
  }
}

::v-deep .video-js .vjs-big-play-button {
  top: 47%;
  left: 47%;
}
</style>
